package command

import (
	"encoding/hex"
	"encoding/json"
	"gdfs-center/db"
	"gdfs-center/engine"
	"gdfs-center/logcat"
	"gdfs-center/socket/cmdGenerate"
	"gdfs-center/socket/codec"
	"log"
)

//上报同步进度
func AnalysisSyncPercent(data *codec.DataDockPackage) {
	var p codec.SyncPercent
	hexbyte, _ := hex.DecodeString(data.Data)
	jsonerr := json.Unmarshal(hexbyte, &p)
	if jsonerr != nil {
		log.Println("###json err:", jsonerr)
	}
	//写入数据库
	var task db.SyncTask
	db.GetDB().Where("task_id = ?", p.TaskId).First(&task)
	if task != (db.SyncTask{}) {
		task.Percent = p.Percent
		task.RecordId = p.RecordId
		if task.Percent == 100 {
			//发送关闭TCP通道命令
			task.Status = 2
			if _, ok := engine.GetEngine().StoreMap[task.StoreId]; ok {
				s := engine.GetEngine().StoreMap[task.StoreId]
				if s.Alive {
					//在线发送
					s.Conn.Write(cmdGenerate.GenerateCloseTcptun(task.TaskId, task.StoreId, task.TargetId))
				}
			}
		}
		//更新数据
		db.GetDB().Save(&task)
	}
}

func AnalysisCreateTcpServerResult(data *codec.DataDockPackage) {
	logcat.GetLog().Sugar().Info("##########收到创建TCP服务成功返回---------------------~!")
	var result codec.CreateTcpServerResult
	hexbyte, _ := hex.DecodeString(data.Data)
	jsonerr := json.Unmarshal(hexbyte, &result)
	if jsonerr != nil {
		log.Println("###json err:", jsonerr)
	}
	var task db.SyncTask
	db.GetDB().Where("task_id = ?", result.TaskId).First(&task)
	if task == (db.SyncTask{}) {
		logcat.GetLog().Sugar().Info("找不到任务记录--------!")
		return
	}
	if result.Code != "0" {
		//不成功就继续发送
		logcat.GetLog().Sugar().Info("创建TCP服务器失败--------!")
		if _, ok := engine.GetEngine().StoreMap[task.StoreId]; ok {
			t := engine.GetEngine().StoreMap[task.TargetId]
			if t.Alive {
				//设备在线
				t.Conn.Write(cmdGenerate.GenerateTcpServer(result.TaskId, task.DbPort))
			}
			return
		}
	}
	logcat.GetLog().Sugar().Info("##########开始发送连接TCP指令---------------------~!")
	//向数据源服务发送迁移指令
	if _, ok := engine.GetEngine().StoreMap[task.StoreId]; ok {
		s := engine.GetEngine().StoreMap[task.StoreId]
		if s.Alive {
			s.Conn.Write(cmdGenerate.GenerateConnTcpServer(task.DbPort, task.TaskId, task.TargetIp))
		}
	}

}
